from WindPy import w
from comm_tools.config import Config
from comm_tools.logger import log_progress
from comm_tools.database_mysql import open_mysql, load_to_MySQL_on_Cloud
from comm_tools import date_tool
import pandas as pd

code_list = ["000001.SH", "DJI.GI", "HSI.HI", "IXIC.GI", "SPX.GI", "N225.GI"]

def format_to_pd(list_data, dates):
    df = pd.DataFrame(list_data)

    df = df.T
    df.columns = code_list

    df['Date'] = dates

    return df

def get_data(date_1, date_2, code):
    w.start()  # 默认命令超时时间为120秒，如需设置超时时间可以加入waitTime参数，例如waitTime=60,即设置命令超时时间为60秒

    # w.isconnected()  # 判断WindPy是否已经登录成功
    # 获取指数
    returned_data = w.wsd(code, "close", date_1, date_2, "Days=Alldays")
    # 检查数据是否成功获取
    if returned_data.ErrorCode == 0:
        log_progress(f"指数收盘价为：{returned_data.Data}")
        log_progress(f"对应的时间为：{returned_data.Times}")
    else:
        log_progress("数据获取失败，请检查日期是否正确或网络连接。")

    return format_to_pd(returned_data.Data, returned_data.Times)

def save_data(df_data, table_name):
    with open_mysql() as engine:
        load_to_MySQL_on_Cloud(df_data, engine, table_name)


def upload():
    # e.g. '2025-01-01'
    start_date = date_tool.get_first_day_of_previous_month()
    # e.g. '2025-01-31'
    end_date = date_tool.get_last_day_of_previous_month()

    data = get_data(start_date, end_date, code_list)

    c = Config()
    save_data(data, c.table_index_a)